import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import ResizeTable from 'components/resize-table'
import { Form, Badge, Row, Col, message, Pagination } from 'antd'
import moment from 'moment';
import periodControlService from 'containers/finance-setting/account-period-control/account-period-control.service'

class AccountPeriodDetail extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      periodInfo: {},
      periodInfoList: [
        {label: messages('finance-setting.key3'/*会计期代码*/), id: 'periodSetCode'}, //会计期代码
        {label: messages('finance-setting.key9'/*会计期名称*/), id: 'periodSetName'}, //会计期名称
        {label: messages('finance-setting.key10'/*期间总数*/), id: 'totalPeriodNum'}, //期间总数
        {label: messages('finance-setting.key1'/*账套代码*/), id: 'setOfBooksCode'}, //账套代码
        {label: messages('finance-setting.key2'/*账套名称*/), id: 'setOfBooksName'} //账套名称
      ],
      columns: [
        {title: messages('finance-setting.key11'/*年*/), key: 'periodYear', dataIndex: 'periodYear'}, //年
        {title: messages('common.sequence'), key: 'periodNum', dataIndex: 'periodNum'},  //序号
        {title: messages('finance-setting.key12'/*日期从*/), key: 'startDate', dataIndex: 'startDate',
          render: date => moment(date).format('YYYY-MM-DD')},  //日期从
        {title: messages('finance-setting.key13'/*日期至*/), key: 'endDate', dataIndex: 'endDate',
          render: date => moment(date).format('YYYY-MM-DD')},  //日期至
        {title: messages('finance-setting.key14'/*季度*/), key: 'quarterNum', dataIndex: 'quarterNum'},  //季度
        {title: messages('finance-setting.key15'/*期间*/), key: 'periodName', dataIndex: 'periodName'},  //期间
        {title: messages('finance-setting.key16'/*期间状态*/), key: 'periodStatusCode', dataIndex: 'periodStatusCode',
          render: code => (
            <Badge status={code==='O' ? 'success' : 'error'}
                   text={code==='N' ? messages('finance-setting.key17'/*未打开*/) :
                     (code==='O' ? messages('finance-setting.key18'/*已打开*/) :
                       messages('finance-setting.key19'/*已关闭*/))}
            />
          )},  //期间状态
        {title: messages('common.operation'), key: 'id', dataIndex: 'id',
          render: (periodId, record) =>
            <a onClick={() => {this.operaPeriodStatus(periodId, record.periodSetId, record.periodStatusCode)}}>
              {record.periodStatusCode === 'O' ? messages('finance-setting.key20'/*关闭期间*/) :
                messages('finance-setting.key21'/*打开期间*/)}
            </a>},  //操作
      ],
      dataClose: [],
      dataOpen: [],
      pageClose: 0,
      pageOpen: 0,
      pageSizeClose: 5,
      pageSizeOpen: 5,
      paginationClose: {
        total: 0
      },
      paginationOpen: {
        total: 0
      },
      loadingClose: false,
      loadingOpen: false,
    };
  }

  componentWillMount() {
    this.getPeriodInfo();
    this.getClosedList();
    this.getOpenList();
  }

  getPeriodInfo = () => {
    periodControlService.getAccountPeriodInfo(this.props.params.periodSetId, this.props.params.setOfBooksId).then((res) => {
      this.setState({ periodInfo: res.data })
    }).catch(e => {

    })
  };

  getClosedList = () => {
    const { pageClose, pageSizeClose } = this.state;
    const { periodSetId, setOfBooksId } = this.props.params;
    this.setState({ loadingClose: true });
    periodControlService.getClosePeriod(pageClose, pageSizeClose, periodSetId, setOfBooksId).then((res) => {
      this.setState({
        dataClose: res.data,
        loadingClose: false,
        paginationClose: {
          total: Number(res.headers['x-total-count']),
          onChange: this.onChangeClosePage,
          pageSize: this.state.pageSizeClose
        }
      })
    }).catch(() => {
      this.setState({ loadingClose: false });
      message.error(messages('common.error1'))
    })
  };

  getOpenList = () => {
    const { pageOpen, pageSizeOpen } = this.state;
    const { periodSetId, setOfBooksId } = this.props.params;
    this.setState({ loadingOpen: true });
    periodControlService.getOpenPeriod(pageOpen, pageSizeOpen, periodSetId, setOfBooksId).then((res) => {
      this.setState({
        dataOpen: res.data,
        loadingOpen: false,
        paginationOpen: {
          total: Number(res.headers['x-total-count']),
          onChange: this.onChangeOpenPage,
          pageSize: this.state.pageSizeOpen
        }
      })
    }).catch(() => {
      this.setState({ loadingOpen: false });
      message.error(messages('common.error1'))
    })
  };

  //点击未打开状态的页码
  onChangeClosePage = (page) => {
    if(page - 1 !== this.state.pageClose) {
      this.setState({
        pageClose: page - 1,
        loadingClose: true
      }, () => {
        this.getClosedList();
      })
    }
  };

  //点击已打开状态的页码
  onChangeOpenPage = (page) => {
    if(page - 1 !== this.state.pageOpen) {
      this.setState({
        pageOpen: page - 1,
        loadingOpen: true
      }, () => {
        this.getOpenList();
      })
    }
  };

  //修改未打开状态每页显示的数量
  onShowCloseSizeChange = (current, pageSize) => {
    this.setState({
      pageClose: current - 1,
      pageSizeClose: pageSize
    },()=>{
      this.getClosedList()
    })
  };

  //修改已打开状态每页显示的数量
  onShowOpenSizeChange = (current, pageSize) => {
    this.setState({
      pageOpen: current - 1,
      pageSizeOpen: pageSize
    },()=>{
      this.getOpenList()
    })
  };

  //修改期间状态：打开 <=> 关闭
  operaPeriodStatus = (periodId, periodSetId, status) => {
    periodControlService.operaPeriodStatus(status === 'O' ? 'close' : 'open', periodId, periodSetId, this.props.params.setOfBooksId).then(res => {
      if (res.status === 200) {
        this.getClosedList();
        this.getOpenList();
        message.success(messages('common.operate.success')/* 操作成功 */)
      }
    }).catch(e => {
      message.error(`${messages('common.operate.filed')/* 操作失败 */}，${e.response.data.message}`)
    })
  };

  render(){
    
    const { periodInfo, periodInfoList, columns, dataClose, dataOpen, paginationClose, paginationOpen, loadingClose, loadingOpen, pageSizeClose, pageSizeOpen } = this.state;
    let periodRow = [];
    let periodCol = [];
    periodInfoList.map((item, index) => {
      periodCol.push(
        <Col span={8} style={{marginBottom: '15px'}} key={item.id}>
          <div style={{color: '#989898'}}>{item.label}:</div>
          <div style={{wordWrap:'break-word'}}>{periodInfo[item.id]}</div>
        </Col>
      );
      if (index === 2) {
        periodRow.push(
          <Row style={{background:'#f7f7f7',padding:'20px 25px 0',borderRadius:'6px'}} key="1">
            {periodCol}
          </Row>
        );
        periodCol = [];
      }
      if (index === 4) {
        periodRow.push(
          <Row style={{background:'#f7f7f7',padding:'0 25px 5px',borderRadius:'6px'}} key="2">
            {periodCol}
          </Row>
        );
      }
    });
    return (
      <div className="account-period-detail">
        <h3 className="header-title">{messages('finance-setting.key22'/*账套期间信息*/)}</h3>
        {periodRow}
        <h3 className="header-title" style={{margin:'24px 0 10px'}}>{messages('finance-setting.key23'/*会计期间-未打开*/)}</h3>
        <ResizeTable
          rowKey={record => record.id}
          columns={columns}
          dataSource={dataClose}
          pagination={false}
          loading={loadingClose}
          bordered
          size="middle"
        />
        <Pagination size="small"
                    showSizeChanger
                    onShowSizeChange={this.onShowCloseSizeChange}
                    defaultPageSize={pageSizeClose}
                    pageSizeOptions={['5','10','20','30','50']}
                    style={{float:'right',margin:'10px 0'}}
                    onChange={this.onChangeClosePage}
                    total={paginationClose.total} />
        <h3 className="header-title" style={{margin:'40px 0 10px'}}>{messages('finance-setting.key24'/*会计期间-已打开*/)}</h3>
        <ResizeTable
          rowKey={record => record.id}
          columns={columns}
          dataSource={dataOpen}
          pagination={false}
          loading={loadingOpen}
          bordered
          size="middle"
        />
        <Pagination size="small"
                    showSizeChanger
                    onShowSizeChange={this.onShowOpenSizeChange}
                    defaultPageSize={pageSizeOpen}
                    pageSizeOptions={['5','10','20','30','50']}
                    style={{float:'right',margin:'10px 0 50px'}}
                    onChange={this.onChangeOpenPage}
                    total={paginationOpen.total} />
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {}
}

const WrappedAccountPeriodDetail = Form.create()(AccountPeriodDetail);

export default connect(mapStateToProps)(WrappedAccountPeriodDetail);
